/*
 * Copyright (c) 2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
'use strict';
import axios from "axios"
import FormData from './src/js/FormData'
import {http, request} from './src/js/index'
import transformRequest from './src/js/transformRequest'
import AxiosError from './node_modules/axios/lib/core/AxiosError'
import fileio from '@ohos.fileio';

axios.defaults.transformRequest = function(data, headers){
    return transformRequest(data, headers)
}

axios.defaults.adapter = function (config) {
    return new Promise(function (resolve, reject) {

        if(config.data && config.data instanceof FormData && config.method.toUpperCase() === 'POST'){
           // 上传
           request.upload(config, resolve, reject);
        }else if(config.filePath && config.method.toUpperCase() === 'GET'){
           // 下载。如果文件已存在，则直接返回错误。
           try {
               fileio.accessSync(config.filePath);
               reject(new AxiosError('The file already exist, please delete the file first!', null, null, null, null));
           } catch(err) {
               request.download(config, resolve, reject);
           }
        }else {
           // 发送请求
           http(config, resolve, reject);
        }
    });
}

export {axios, FormData}
